<?php
namespace app\common\model;
use think\Model;
use PHPQRCode\QRcode;

/**
 * 会员模型
 */
class User extends Model {
	protected $selectField = 'id,number,account,password,nick_name,sex,birthday,zhiye,grade,openid,token,disabled,qrcode,im_password,position_num,im_account,photo_path';



	protected static function init(){
		self::beforeInsert(function($data){
			$data['im_account'] = $data['token'] = time().rand(1000,9999); 
			$data['register_time'] = time();
			$data['qrcode'] = model('common/user')->createQrcode($data['token']);
			//手机号注册
			if($data['register_type'] == 1){
				$data['im_password'] = $data['password'];
			}else{ //第三方登录
				$data['im_password'] = md5(date('YmdHis').$data['register_type']);
			}

			if(isset($data['birthday']) && $data['birthday']){
				$im['birthday'] = $data['birthday'];
				$data['birthday'] = strtotime($data['birthday']);
				$data['age'] = intval(date('Y')-date('Y',$data['birthday']));
			}

			if(isset($data['nick_name']) && $data['nick_name']){
				$im['nickname'] = $data['nick_name'];
			}

			if(isset($data['sex']) && in_array($data['sex'],[0,1,2])){
				$im['gender'] = $data['sex'];
			}
			//注册极光im
			
			$res = im_register($data['im_account'],$data['im_password']);
			if($res['status'] == 0) {
				return false;
			}

			if(!empty($im)){
				//修改信息
				$res = im_update($data['im_account'],$im);
				if($res['status'] == 0){
		
					return false;
				}
			}

		});
		self::afterInsert(function($data){
			db('user')->where('id',$data['id'])->update(['number' => $data['id'] + 10000]);
		});

		self::beforeUpdate(function($data){
			$data['update_time']  = time();
			if(isset($data['birthday']) && $data['birthday']){
				$im['birthday'] = $data['birthday'];
				$data['birthday'] = strtotime($data['birthday']);
				$data['age'] = intval(date('Y')-date('Y',$data['birthday']));
			}
			if(isset($data['nick_name']) && $data['nick_name']){
				$im['nickname'] = $data['nick_name'];
			}

			if(isset($data['sex']) && in_array($data['sex'],[0,1,2])){
				$im['gender'] = $data['sex'];
			}
			if(!empty($im)){
				//修改信息
				$res = im_update($data['im_account'],$im);
				if($res['status'] == 0){
					return false;
				}
			}
		});
	}

	

	/**
	 * [会员信息]
	 * @param  array  $where [条件]
	 * @param  string $filed [字段]
	 * @return [array]        [description]
	 */
	public function getUserInfo($where=[],$field=''){

		if($field === ''){
			$field = $this->selectField;
		}

		$user = db('user')->where($where)->field($field)->find();
		if(isset($user['token'])){
			$Aes = new \Aes\Aes();
        	$token = $Aes->aes128cbcEncrypt($user['token']);
			$user['token'] = $token;
		}

		if(isset($user['photo_path']) && $user['photo_path'] && strpos($user['photo_path'],'http') === false){
			$user['photo_path'] = config('http_server').$user['photo_path'];
		}

		if(isset($user['qrcode'])){
			$user['qrcode'] = config('http_server').$user['qrcode'];
		}
		
		if(isset($user['birthday'])){

			$user['birthday'] = $user['birthday'] == 0 ? '' : date('Y-m-d',$user['birthday']);
		}

		if(isset($user['cia'])){
			$user['cia'] = empty($user['cia']) ? [] : explode(',',$user['cia']) ;
		}

		if(isset($user['grade']) && isset($user['grade_end_time'])){
			if($user['grade'] == 1){
				if($user['grade_end_time'] < strtotime(date('Y-m-d'))){
					$user['grade_end_time'] = '';
					$user['grade'] = 0;
				}else{
					$user['grade_end_time'] = date('Y-m-d',$user['grade_end_time']);
				}
			}else{
				$user['grade_end_time'] = '';
			}
		}

		if(isset($user['tag'])){
			$user['tag'] = $user['tag'] == '' ? [] : explode(',',$user['tag']);
		}
		//职业
		if(isset($user['zhiye'])){
			$user['zhiye'] = $user['zhiye'] == 0 ? '' : db('zhiye')->where('id',$user['zhiye'])->value('name');
		}

		//行业
		if(isset($user['hangye'])){
			$user['hangye'] = $user['hangye'] == 0 ? '' : db('hangye')->where('id',$user['hangye'])->value('name');
		}

		return $user;
	}


	/**
	 * [生成二维码]
	 * @param  integer $user_id [当前会员id]
	 * @return [type]           [description]
	 */
	public function createQrcode($user_id=0){
		@mkdir(ROOT_PATH . 'public' . DS . 'qrcode');
        $qrcode = md5(time() . mt_rand(100000, 999999)) . '.png';
        QRcode::png($user_id, ROOT_PATH . 'public' . DS . 'qrcode' . DS . $qrcode);
        $qrcode = '/qrcode/' . $qrcode;
        return $qrcode;
	}

	/**
	 * [登录前置操作]
	 * @param  string  $lng  [当前经度]
	 * @param  string  $lat  [当前纬度]
	 * @param  string  $city [所在城市]
	 * @param  integer $id   [description]
	 * @return [type]        [description]
	 */
	public function loginBeforeHandle($id=0,$token=''){
		$this->save([
			'last_login_time' => time(),
			'token' => $token
		],['id'=>$id]);
	}

	/**
	 * [delData 删除隐私数据]
	 * @param  array  $data [原数据]
	 * @param  array  $keys [删除指定下标]
	 * @return [type]       [description]
	 */
	public function delData($data = [],$keys = []){
		foreach($keys as $key => $val){
			if(isset($data[$val])){
				unset($data[$val]);
			}
		}
		return $data;
	}


	/**
	 * [userList 帮主列表]
	 * @param  array   $where 		[description]
	 * @param  string  $order 		[description]
	 * @param  integer $p    		[description]
	 * @param  string  $lng   		[description]
	 * @param  string  $lat   		[description]
	 * @param  string  $page_size   [description]
	 * @return [type]         		[description]
	 */
	public function userList($where = [],$order = 'juli asc',$p = 0,$lng = '',$lat = '',$page_size = 0){
		if($page_size == 0){
			$page_size = config('page_size');
		}
        $field = "id,nick_name,photo_path,zhiye,kaopu,tag,service_count,ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(( $lat * PI() / 180 - from_lat * PI() / 180) / 2),2) + COS($lat * PI() / 180) * COS(from_lat * PI() / 180) * POW(SIN(($lng * PI() / 180 - from_lng * PI() / 180) / 2),2)))) AS juli,sex";
        
		$this->alias('u')->where('disabled',1)->where($where)
			->order($order)
			->field($field);

		if($p > 0){
			$this->limit(($p-1)*$page_size,$page_size);
		}
		$list = $this->select();

		foreach($list as $key => $val){
			$list[$key]['tag'] = $val['tag'] == '' ? [] : explode(',',$val['tag']);

		
			$list[$key]['zhiye'] = $val['zhiye'] == 0 ? '' : db('zhiye')->where('id',$val['zhiye'])->value('name');
		
		}

		return $list;
	}


	//地图帮主列表
	public function userByMap($where = [],$lng = '',$lat = '',$having = '',$user_id = 0){
		$list = $this->alias('u')->join(['bz_user_position' => 'p'],'p.user_id = u.id')
			->where('u.disabled',1)->where($where)
			->field("u.id,nick_name,photo_path,zhiye,service_count,kaopu,ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(( $lat * PI() / 180 - lat * PI() / 180) / 2),2) + COS($lat * PI() / 180) * COS(lat * PI() / 180) * POW(SIN(($lng * PI() / 180 - lng * PI() / 180) / 2),2)))) AS juli,tag,lng,lat")
			->having($having)
			->select();
	
		$zhiye = db('zhiye');
		foreach($list as $key => $val){
			$list[$key]['zhiye'] = $val['zhiye'] == 0?'':$zhiye->where('id',$val['zhiye'])->value('name');
			$list[$key]['tag'] = $val['tag'] == '' ? [] : explode(',',$val['tag']);
			$list[$key]['guanzhu'] = 0;
			if($user_id > 0){
				if(db('user')->where('user_id',$user_id)->where('care_id',$val['id'])->find()){
					$list[$key]['guanzhu'] = 1;
				}
			}

		}

		return $list;
	}
}
